%% Newton's Method for finding a Zero-Crossing

%web('https://en.wikipedia.org/wiki/Newton''s_method')


%Setup a function that crosses zero
X=(-.5:.1:2)
f=@(x).5-exp(-x)
f_p=@(x)exp(-x)

%Show the function.  We can see it crosses zero
figure
plot(X,f(X))
xlabel('X')
xlabel('f(X)')

%Apply the iterative method until we reach a specified tolerance.
TolF=eps;
clear XN %to prevent writing into an existing array.  
%XN=[]; %We could also do this. 

%Starting point (guess) 
X0=1; 
XN(1)=X0;

D=2*TolF;  %Make sure are variable under test is larger than tolerance for first loop

Cnt=1; %Our increment variable

while D>TolF %Keep running Newton's method until we reach tolerance
    
    %This is the main update 
    XN(Cnt+1)=XN(Cnt) - f(XN(Cnt))/f_p(XN(Cnt)); %write into next element of array
    D = abs(f(XN(Cnt+1))); %Calcualte distance from zero
    
    %Plot in existing figure. 
    hold off
    plot(X,f(X))
    hold on
    plot([XN(Cnt),XN(Cnt+1)],f([XN(Cnt),XN(Cnt+1)]),'r','linewidth',3)
    s=sprintf('X: %g F(X): %g',XN(Cnt+1),f(XN(Cnt+1)))
    text(XN(Cnt+1),f(XN(Cnt+1))+.1,s)
    pause(2)
    
    Cnt=Cnt+1; %update increment variable
    
end

fprintf('Found a zero crossing at: %g after %d iterations\n',XN(end),Cnt)







